package com.yueyang.sojourn.server.service.share;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.common.baymax.web.result.exception.StandardBusinessException;
import com.yueyang.sojourn.server.model.dto.DistributorImportDto;
import com.yueyang.sojourn.server.model.enums.ShareDistributorStatusEnum;
import com.yueyang.sojourn.server.model.po.ShareDistributor;
import com.yueyang.sojourn.server.model.vo.DistributorImportResultVo;
import com.yueyang.sojourn.server.model.vo.ShareDistributorVo;
import com.yueyang.sojourn.server.service.FileService;
import com.yueyang.sojourn.server.utils.PhoneNumberUtil;
import com.yueyang.uc.UserType;
import com.yueyang.uc.model.UcUserV1;
import com.yueyang.uc.spi.UserSpi;
import jk.excel.parse.Excel;
import jk.excel.parse.ExcelParseFactory;
import jk.excel.parse.Mapping;
import jk.excel.parse.ParseInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分销人service
 * @author Stephen.Shi
 * @since 2020/05/02
 */
@Service
public class ShareDistributorService {
    @Autowired
    private ShareDistributorMapper shareDistributorMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserSpi userSpi;

    private static final String ERR_DUMP_TEMPLATE  = "第%s行导入失败，手机号已存在；";
    private static final String ERR_INVALID_TEMPLATE  = "第%s行导入失败，手机号格式不对；";
    private static final String ERR_UNREGIST_TEMPLATE  = "第%s行导入失败，手机号还未注册，请先到小程序中完成注册；";

    public ShareDistributor findByUserId(Long userId) {
        return this.shareDistributorMapper.selectByPrimaryKey(userId);
    }

    /**
     * 是否是分销员
     * @param userId
     * @return
     */
    public boolean isDistributor(Long userId) {
        ShareDistributor distributor = this.findByUserId(userId);
        return distributor != null && distributor.getState() == 1 && distributor.getStatus() == ShareDistributorStatusEnum.已启用.getValue();
    }

    /**
     * 列表搜索
     * @param status
     * @param keyword
     * @param pageSize
     * @param pageNum
     * @return
     */
    public PageInfo<ShareDistributorVo> findList(ShareDistributorStatusEnum status, String keyword, int pageSize, int pageNum) {
        Integer statusint = status == null ? null : status.getValue();
        PageInfo<ShareDistributorVo> pageInfo = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> this.shareDistributorMapper.findList(statusint, keyword));
        pageInfo.getList().stream().forEach(vo -> {
            UcUserV1 cuserv1 = userSpi.findById(vo.getCuser());
            if (cuserv1 != null) {
                vo.setCUserName(cuserv1.getUserName());
//                vo.setPhone(PhoneNumberUtil.getSecPhone(vo.getPhone()));
            }
        });
        return pageInfo;
    }

    /**
     * 修改状态
     */
    public void updateStatus(Long userId, ShareDistributorStatusEnum status, Long operator) {
        ShareDistributor distributor = this.findByUserId(userId);
        JAssert.pass(distributor != null, "分销人不存在");
        distributor.setStatus(status.getValue());
        distributor.setMtime(new Date());
        distributor.setMuser(operator);
        this.shareDistributorMapper.updateByPrimaryKey(distributor);
    }

    public DistributorImportResultVo dataImport(String fileName, long cuser) {
        File file = fileService.getFile(fileName);
        List<Mapping> mappings = getMappings();;
        ParseInfo info = new ParseInfo(file, 2, true);
        info.setMappings(mappings);
        Excel excel = ExcelParseFactory.getExcelParse(info);
        List<DistributorImportDto> list = null;
        try {
            list = excel.parseToList(DistributorImportDto.class);
        } catch (Exception e) {
            throw new StandardBusinessException("所选文件与导入模板不匹配，请按照导入模板重新编辑");
        }
        List<String> phoneList = list.stream().map(DistributorImportDto::getPhone).distinct().collect(Collectors.toList());

        List<UcUserV1> userV1List = new ArrayList<>();
        Lists.partition(phoneList, 100).stream().forEach(slice -> {
            String phones = slice.stream().reduce((s1, s2) -> s1 + "," + s2).orElse("");
            if (StringUtils.isNotBlank(phones))  {
                userV1List.addAll(userSpi.findByPhones(phones, UserType.微信用户.getValue()));
            }
        });

        Map<String, UcUserV1> phoneUserMap = userV1List.stream().collect(Collectors.toMap(UcUserV1::getPhone, ucUserV1 -> ucUserV1));

        List<Integer> phoneValidError = new ArrayList<>();
        List<Integer> phoneDumplicateError = new ArrayList<>();
        List<Integer> phoneUnRegistError = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();
        int successCount = 0;
        for(int i=0; i<list.size(); i++) {
            DistributorImportDto dto = list.get(i);
            // 不合法的手机号
            if (!PhoneNumberUtil.isPhoneNumber(dto.getPhone())) {
                phoneValidError.add(i + 2);
                errorMessages.add(String.format(ERR_INVALID_TEMPLATE, i+2));
            }

            else {
                UcUserV1 ucUserV1 = phoneUserMap.get(dto.getPhone());
                // 用户未注册校验
                if (ucUserV1 == null) {
                    phoneUnRegistError.add(i + 2);
                    errorMessages.add(String.format(ERR_UNREGIST_TEMPLATE, i+2));
                } else {
                    // 重复的手机号校验
                    ShareDistributor distributor = this.findByUserId(ucUserV1.getId());
                    if (distributor != null) {
                        phoneDumplicateError.add(i + 2);
                        errorMessages.add(String.format(ERR_DUMP_TEMPLATE, i+2));
                    }
                    else {
                        distributor = new ShareDistributor();
                        distributor.setCtime(new Date());
                        distributor.setCuser(cuser);
                        distributor.setMtime(new Date());
                        distributor.setMuser(cuser);
                        distributor.setStatus(ShareDistributorStatusEnum.已启用.getValue());
                        distributor.setState(1);
                        distributor.setUserId(ucUserV1.getId());
                        this.shareDistributorMapper.insert(distributor);
                        successCount++;
                    }
                }
            }
        }

        DistributorImportResultVo resultVo = new DistributorImportResultVo();
        resultVo.setSuccessCount(successCount);
        resultVo.setFailCount(list.size() - successCount);
        resultVo.setIsAllSuccess(resultVo.getFailCount() == 0);
        resultVo.setPhoneDumplicateError(phoneDumplicateError);
        resultVo.setPhoneUnRegistError(phoneUnRegistError);
        resultVo.setPhoneValidError(phoneValidError);
        resultVo.setErrorMessages(errorMessages);
        return resultVo;
    }

    private List<Mapping> getMappings() {
        List<Mapping> mps = new ArrayList<Mapping>();
        mps.add(new Mapping("phone", "手机号"));
        return mps;
    }
}
